<template>
  <div class="config">
    <el-row v-if="platform === 'web'">
      <el-col :span="8" v-if="platform === 'web'">{{$t('configLazyLoad.channel.welcomeMsgPush')}}:</el-col>
      <el-col :span="platform === 'web' ? 16 : 8">
        <div>
          <el-radio class="radio" v-model="welcomeMsgPush" :label="true">{{$t('public.yes')}}</el-radio>
          <el-radio class="radio" v-model="welcomeMsgPush" :label="false">{{$t('public.no')}}</el-radio>
        </div>
        <div class="desc row-top">{{$t('configLazyLoad.channel.welcomeTip1')}}</div>
      </el-col>
    </el-row>
    <el-form-item v-if="platform === 'sdk'" :label="$t('configLazyLoad.channel.welcomeMsgPush')+'：'">
      <el-radio-group v-model="welcomeMsgPush">
        <el-radio :label="true">{{$t('public.yes')}}</el-radio>
        <el-radio :label="false">{{$t('public.no')}}</el-radio>
      </el-radio-group>
      <div class="desc row-top">{{$t('configLazyLoad.channel.welcomeTip1')}}</div>
    </el-form-item>
    <el-row class="row-top" v-show="welcomeMsgPush">
      <div id="agentWelcomeMsgEditorMenu"></div>
      <div id="agentWelcomeMsgEditorCon"></div>
      <div class="remark row-top">
        <span>{{$t('configLazyLoad.channel.webStyleTip5')}}</span>
        <el-tooltip class="item" effect="dark" popper-class="reportTip" placement="bottom" style="opacity: 1;">
          <div slot="content">
            {{$t('configLazyLoad.channel.webStyleTip6')}}
          </div>
          <span class="tip"><i class="iconfont icon-tixingweizhi"></i></span>
        </el-tooltip>
      </div>
      <div class="placeholder_box">
        <dl v-for="place in placeholderArr" @click="addPlaceholder(place.data)" :title="place.content">
          {{place.content}}
          <i class="iconfont icon-zhankai"></i>
        </dl>
      </div>
    </el-row>
  </div>
</template>
<script>
  import Editor from 'wangeditor'
  import * as uuid from 'uuid'
  import {uploadTo7moorEmailDomain} from '@utils/qiniuUtils'
  import { deepClone, filterXSS } from '@utils/m7Utils.js'
  export default {
    name: 'welcomeMsgEditBox',
    data () {
      return {
        editor: {},
        m7uploaders: [],
        welcomeMsgPush: false,
        welcomeMsgCon: '',
        placeholderArr: [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }, {
            content: this.$t('configLazyLoad.channel.agent'),
            data: 'agent'
          }, {
            content: this.$t('configLazyLoad.channel.agentName'),
            data: 'agentName'
          }, {
            content: this.$t('configLazyLoad.channel.agentNickName'),
            data: 'agentNickName'
          }, {
            content: this.$t('configLazyLoad.channel.agentPhone'),
            data: 'agentPhone'
          }
        ]
      }
    },
    methods: {
      initUploadImageFile () {
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          console.log('uploadProgress1')
        }
        let uploadComplete = function () {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          // self.editor.txt.append('<img src="' + sourceLink + '" alt="">')
          // 改为图片在光标出插入
          self.editor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
          self.welcomeMsgCon = self.editor.txt.html()
        }
        let error = function (up, err, errTip) {
          self.$message.error(errTip)
        }
        let key = function (up, file) {
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          let key = 'email/' + time + '/' + uuid.v1() + '/' + fileName
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp'}
          ]
        }
        this.m7uploaders.push(
          uploadTo7moorEmailDomain(this.sessionUserId, 'w-agent-node-img-icon', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
        )
      },
      addPlaceholder (data) {
        let dataNew = ''
        let content = this.editor.txt.html()
        content = content.replace(/<p><br><\/p>/g, '')
        content = content.substring(0, content.length - 4)
        console.log(content)
        if (!content) {
          dataNew = '<p>{' + data + '}</p>'
        } else {
          dataNew = content + '{' + data + '}</p>'
        }
        this.editor.txt.html(filterXSS(dataNew))
        this.welcomeMsgCon = dataNew
      }
    },
    props: {
      agentWelMsgPush: {
        type: Boolean,
        default: false
      },
      platform: String,
      formId: {
        type: String,
        default: ''
      },
      agentWelMsgCon: String
    },
    activated () {
      if (this.formId) {
        this.welcomeMsgPush = deepClone(this.agentWelMsgPush)
        this.welcomeMsgCon = deepClone(this.agentWelMsgCon)
        this.editor.txt.html('')
        this.editor.txt.html(filterXSS(this.welcomeMsgCon))
      } else {
        this.welcomeMsgPush = false
        this.welcomeMsgCon = ''
        this.editor.txt.html('')
      }
    },
    mounted () {
      this.editor = new Editor('#agentWelcomeMsgEditorMenu', '#agentWelcomeMsgEditorCon')
      this.editor.config.menus = [
        'head',  // 标题
        'bold',  // 粗体
        'fontSize',  // 字号
        'fontName',  // 字体
        'italic',  // 斜体
        'underline',  // 下划线
        'strikeThrough',  // 删除线
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'justify'  // 对齐方式
      ]
      this.editor.config.pasteTextHandle = filterXSS
      this.editor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
      let that = this
      let lang = window.langJson || {}
      let editLang = lang.wangeditor
      this.editor.config.lang = editLang
      this.editor.config.onchange = (html) => {
        // html 即变化之后的内容
        if (new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(this.welcomeMsgCon)) {
          this.welcomeMsgCon = this.welcomeMsgCon.replace(/<table border="0" width="100%" cellpadding="0" cellspacing="0">/g, '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">')
        }
        this.welcomeMsgCon = that.editor.txt.html()
      }
      this.editor.config.zIndex = 100
      this.editor.create()
      this.editor.txt.html(filterXSS(this.welcomeMsgCon))
      let div = document.createElement('div')
      div.className = 'w-e-menu'
      div.style.cssText = 'z-index:101;'
      let span = document.createElement('i')
      span.className = 'w-e-icon-image'
      span.id = 'w-agent-node-img-icon'
      div.appendChild(span)
      document.getElementsByClassName('w-e-toolbar')[0].appendChild(div)
      this.initUploadImageFile()
      this.welcomeMsgPush = deepClone(this.agentWelMsgPush)
      this.welcomeMsgCon = deepClone(this.agentWelMsgCon)
      this.editor.txt.html(filterXSS(this.welcomeMsgCon))
    },
    beforeMount () {
      this.welcomeMsgPush = deepClone(this.agentWelMsgPush)
      this.welcomeMsgCon = deepClone(this.agentWelMsgCon)
    },
    beforeDestroy () {
      this.$_uploaders.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  #agentWelcomeMsgEditorCon
    border 1px solid #ccc
    border-top none
    height 220px
  .w-e-toolbar
    background-color #f1f1f1
    border 1px solid #ccc
  .desc
    color $c-prompt
    font-size 12px
    line-height 12px
  .row-top
    margin-top 16px
  .placeholder_box
    margin-top 10px
    dl
      border 1px solid $c-main
      color $c-main
      border-radius 6px
      display inline-block
      padding 4px
      margin 0 10px 10px 0
      cursor pointer
    .iconfont
      font-size 12px
  .remark
    color #3b5998
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
</style>